/*
 * @Author: 'hxian' '2232436248@qq.com'
 * @Date: 2025-01-09 11:02:12
 * @LastEditors: 'hxian' '2232436248@qq.com'
 * @LastEditTime: 2025-01-09 11:21:57
 * @FilePath: \vue-project\src\views\map\utils\useCreateArea.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import * as THREE from 'three';
import {useGetMapJson} from "@/views/map/utils/useGetMapJson.js";
import { Line2 } from 'three/examples/jsm/lines/Line2'
import { LineGeometry } from 'three/examples/jsm/lines/LineGeometry'
import { LineMaterial } from 'three/examples/jsm/lines/LineMaterial'
import * as d3 from 'd3';
import BG from '../assets/image/bg.png';

const boxScale =  100;
export async function UseCreateArea(code,name,centroid) {
    let geoJson = await useGetMapJson(code);
    return UseCreateAreaMesh(code,name,centroid,geoJson);
}

    // d3-geo转化坐标
    // 坐标转换
export const projection = d3.geoMercator()
    .center([106.0, 39.5])
    .scale(boxScale)
    .translate([0, 0]);

/**
 * @description 获取投影
 * @param center []
 * @returns {*}
 */
/**
 * @description 创建区域网格对象
 * @constructor
 */
export function UseCreateAreaMesh(code,name,centroid,geoJson){
    const areaMap =  new THREE.Object3D(); // 建一个空对象存放对象
    areaMap.name = name;
    areaMap.adcode = code || null;
    areaMap.centroid = centroid  || [114.298572, 30.584355];
    let texture = new THREE.TextureLoader().load(BG);//加载纹理贴图
    // 禁止纹理纵向翻转
    texture.flipY = true;
    const areaMeshs = new Array();
    const projection = d3.geoMercator()
        .center(centroid || [114.298572, 30.584355])  //动态设置中心点
        .scale(boxScale)
        .translate([0, 0])
    // 遍历省份构建模型
    geoJson.features.forEach(feature => {
        // if (feature.properties.adcode === '100000_JD'){
        //     return
        // }
       feature.geometry.coordinates.forEach(coordinate=>{
           coordinate = coordinate.length > 1 ? [[...coordinate]] : coordinate;
           coordinate.forEach(polygon =>{
               const shape = new THREE.Shape();
               const lineMaterial = new LineMaterial({ color: '#00BFFE', linewidth: 3 })
               const linGeometry = new LineGeometry();
               const pointsArray = new Array();
               for (let i = 0; i < polygon.length; i++) {
                   const [x, y] = projection(polygon[i]);
                   pointsArray.push(new THREE.Vector3(x, -y, 11));
                   if (i === 0) {
                       shape.moveTo(x, -y)
                   }
                   shape.lineTo(x, -y);

               }
               const extrudeSettings = {
                   depth: 10,
                   bevelEnabled: false
               };
               const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings)
               const material = new THREE.MeshBasicMaterial({
                   color: '#c1367e',
                   transparent: false,
                   map: texture})

               // 地图模型侧边材质
              const  mapSideMaterial = new THREE.MeshBasicMaterial({
                   color: "#fff",
                   transparent: true,
                   opacity: 1.0,
               });
               // 侧边材质uniform
               let mapUf = {
                   uTime: { value: 0.0 },
                   uHeight: { value: 10 },
                   uColor: { value: new THREE.Color("#28E6FF" ) }, // 侧边过渡颜色
                   color1: { value: new THREE.Color('#00BFFE') }, // 侧边渐变颜色1
                   color2: { value: new THREE.Color('#0D7DA7') }, // 侧边渐变颜色2
                   uStart: { value: -10 },
                   uSpeed: { value: 10 },
                   uMaxZ: { value: 8 }, // 雷，z轴
                   uOpacity2: { value: 0.05 } // 雷，第二个颜色的透明度
               };

               // 在材质渲染前修改shader代码
               mapSideMaterial.onBeforeCompile = (shader) => {
                   shader.uniforms = {
                       ...shader.uniforms,
                       ...mapUf,
                   };
                   shader.vertexShader = shader.vertexShader.replace(
                       "void main() {",
                       `
                          varying vec3 vPosition;
                          void main() {
                            vPosition = position;
                        `
                   );
                   shader.fragmentShader = shader.fragmentShader.replace(
                       "void main() {",
                       `
                      varying vec3 vPosition;
                      uniform float uTime;
                      uniform vec3 uColor;
                      uniform float uSpeed;
                      uniform float uStart;
                      uniform float uHeight;
                      uniform vec3 color1;
                      uniform vec3 color2;
                       uniform float uMaxZ;// 雷,z轴
                      uniform float uOpacity2; // 雷，第二个颜色的透明度
                      void main() {
                    `
                   );
                   shader.fragmentShader = shader.fragmentShader.replace(
                       "#include <dithering_fragment>",
                       `
                         #include <dithering_fragment>
                        vec3 gradient = mix(color1,color2, vPosition.z/4.0);
                        outgoingLight = outgoingLight*gradient;
                        gl_FragColor = vec4( outgoingLight, diffuseColor.a );
                        #include <dithering_fragment>
                        `
                   );
               };
               // 添加多个线
               linGeometry.setFromPoints(pointsArray);
               const mesh = new THREE.Mesh(geometry, [material,mapSideMaterial])
               mesh.name = feature.properties.name;
               mesh.adcode = feature.properties.adcode;
               mesh.centroid = feature.properties.centroid;
               const line = new Line2(linGeometry, lineMaterial)
               areaMap.add(mesh)
               areaMap.add(line)
               mesh.isListen = true
               areaMeshs.push(mesh);
           })
       })

    })
    const box = new THREE.Box3()
    box.setFromObject(areaMap)
    const size = new THREE.Vector3()
    box.getSize(size); //获取地图包围盒子大小
    let scale =  size.x > boxScale ? 1 : Math.floor( boxScale / size.x); //按照全局盒子大小进行缩放
    // 设置纹理重复
    texture.repeat.set(1 / (size.x + 25), 1 / (size.y + 25))
    // 设置纹理偏移
    texture.offset.set(Math.abs(box.min.x / size.x) + 0.0092, Math.abs(box.min.y / size.y) - 0.092)
    areaMap.userData.listenMesh = areaMeshs;
    areaMap.scale.set(scale, scale,  1)
    return areaMap;
}

export function UseCreateCubeForTest(){
    const geometry = new THREE.BoxGeometry( 1, 1, 1 );
    const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
    const cube = new THREE.Mesh( geometry, material );
    return cube;
}

